package c.w.connection;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import c.w.constants.SystemConstants;

public class ConnInviteService {

	private NioSocketConnector connector = null;
	private IoSession session = null;
	
	public boolean call() {

		int minimumConnectTimeout = 30;
		int port = 2014;
		
		connector = new NioSocketConnector();
		
		DefaultIoFilterChainBuilder chan = connector.getFilterChain();
		
		ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory());
		
		chan.addLast("objFilter", filter);
		
		connector.setHandler(new ConnInviteServiceHandler());
		
		connector.setConnectTimeoutCheckInterval(minimumConnectTimeout);
		
		//根据主机名构建连接
		ConnectFuture cf = connector.connect(new InetSocketAddress(SystemConstants.SERVICE_HOST, port));
		
		cf.awaitUninterruptibly();
		
		session = cf.getSession();
		
		return true;
	}
	
	public boolean close() {
		if (this.session != null) {
			session.getCloseFuture().awaitUninterruptibly(1000);
			
			connector.dispose();
		} else {
			return false;
		}
		
		return true;
	}
	
	public void send(Object obj) {
		session.write(obj);
	}
}
